import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  UseInterceptors,
  ClassSerializerInterceptor,
} from '@nestjs/common';
import { ConfigCalcService } from './config_calc.service';
import { CreateConfigCalcDto } from './dto/create-config_calc.dto';
import { UpdateConfigCalcDto } from './dto/update-config_calc.dto';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { User } from 'src/auth/decorator/user.decorator';
import { UserEntity } from 'src/user/entities/user.entity';
import { BusinessException } from 'src/common/filter/business-exception/business.exception';

@ApiTags('设置参数')
@Controller('config-calc')
export class ConfigCalcController {
  constructor(private readonly configCalcService: ConfigCalcService) {}

  validParam(createConfigCalcDto: CreateConfigCalcDto) {
    createConfigCalcDto.vibrate = Number(createConfigCalcDto.vibrate);
    if ([0, 1].indexOf(createConfigCalcDto.vibrate) < 0)
      throw new BusinessException('开启震动设置错误');
    createConfigCalcDto.vibrate_rate = Number(createConfigCalcDto.vibrate_rate);
    if (
      createConfigCalcDto.vibrate_rate < 0 ||
      createConfigCalcDto.vibrate_rate > 100
    )
      throw new BusinessException('震感范围0-100');
    createConfigCalcDto.mute = Number(createConfigCalcDto.mute);
    if ([0, 1].indexOf(createConfigCalcDto.mute) < 0)
      throw new BusinessException('开启静音设置错误');
    createConfigCalcDto.precision = Number(createConfigCalcDto.precision);
    if (createConfigCalcDto.precision < 0)
      throw new BusinessException('保留小数位设置错误');
    return createConfigCalcDto;
  }

  @Post()
  @ApiOperation({ summary: '创建配置' })
  create(
    @Body() createConfigCalcDto: CreateConfigCalcDto,
    @User() user: UserEntity,
  ) {
    createConfigCalcDto = this.validParam(createConfigCalcDto);
    return this.configCalcService.create(createConfigCalcDto, user);
  }

  // @Get()
  // findAll() {
  //   return this.configCalcService.findAll();
  // }

  @Get()
  @UseInterceptors(ClassSerializerInterceptor)
  @ApiOperation({ summary: '获取配置' })
  findOne(@User() user: UserEntity) {
    return this.configCalcService.findOne(user);
  }

  @Patch()
  @ApiOperation({ summary: '更新配置' })
  @UseInterceptors(ClassSerializerInterceptor)
  update(
    @Body() updateConfigCalcDto: UpdateConfigCalcDto,
    @User() user: UserEntity,
  ) {
    updateConfigCalcDto = this.validParam(updateConfigCalcDto);
    return this.configCalcService.update(updateConfigCalcDto, user);
  }

  // @Delete(':id')
  // remove(@Param('id') id: string) {
  //   return this.configCalcService.remove(+id);
  // }
}
